<template>
  <div class="read-rz">
    <loading v-if="!aggregateData._id" />
    <div class="rz-wrapper" v-else>
      <div class="user">
        <user-info :userInfo="aggregateData.user[0]" @sendMessage="sendMessage"></user-info>
        <div class="allrz">
          <div class="title">
            <h3>TA的日志列表</h3>
          </div>
          <div class="item">
            <ul class="item-slide">
              <li
                :class="data._id === id ? 'active' : ''"
                v-for="data in aggregateData.allrz"
                @click="gotoThis(data._id)"
                :key="data._id"
              >
                <span class="label">{{data.label}}</span>
                <span class="date">{{data.updated | setDate}}</span>
              </li>
            </ul>
          </div>
        </div>
        <bei />
      </div>
      <div class="rz-content">
        <div class="author-info-data">
          <div class="label">
            <div class="name">
              <span>{{aggregateData.label}}</span>
              <span class="star">
                点赞数：
                <i>{{aggregateData.stars | starsFilters}}</i>
              </span>
            </div>
            <div class="date">
              <span>{{aggregateData.userName}}</span>
              <p>
                <span>更新日期：{{aggregateData.updated | setDate}}</span>
                <span>创建日期：{{aggregateData.created | setDate}}</span>
              </p>
            </div>
          </div>
          <div class="body">
            <div class="body-wrapper">
              <div class="img">
                <img :src="aggregateData.url | squareUrls" alt />
              </div>
              <p>{{aggregateData.body}}</p>
            </div>
          </div>
        </div>
        <div class="comment" id="/comment-box">
          <send-message
            ref="sendMessageElement"
            :userInfoData="userInfoData"
            @sendCommentData="sendCommentData"
          ></send-message>
          <ul>
            <li v-for="(comment,index) in aggregateData.comment" :key="comment._id">
              <div class="comment-show">
                <div class="cover">
                  <img :src="comment.sendUserCoverUrl | squareUrls" alt />
                </div>
                <span class="userName">{{comment.sendUserName}}</span>
                <span>评论时间：{{comment.created | setDate}}</span>
                <!-- <span class="z-index">~{{comment.commentChild.length - index}}楼</span> -->
                <div class="btn">
                  <el-badge
                    :value="aggregateData.stars | commentStarFilters(comment)"
                    class="badge"
                  >
                    <el-button size="mini" @click="commentStar(comment.rzCommentId)">赞</el-button>
                  </el-badge>
                  <el-button class="return-omment" size="mini" @click="showReturnArea(index)">回复</el-button>
                </div>
              </div>
              <div class="comment-body">{{comment.rzCommentData}}</div>
              <div class="comment-wrapper" v-if="index === flog1 && flogBox1">
                <first-comment-box
                  :userInfoData="userInfoData"
                  :userName="userName"
                  @_sendReturnCommentData="_sendReturnCommentData"
                ></first-comment-box>
              </div>
              <div class="comment-child">
                <ul>
                  <li v-for="(returns,index2) in comment.child" :key="returns._id">
                    <div class="return-user">
                      <p>
                        {{returns.returnUserName}} 回复：
                        <strong>{{returns.userUserName}}</strong> 的
                        <i>{{returns.rzCommentData}}</i>
                      </p>
                      <div class="return-text">
                        <p>{{returns.returnText}}</p>
                      </div>
                    </div>
                    <div class="return-right">
                      <p>{{returns.updated | setDate}}</p>
                      <el-button size="mini" @click="showReturnArea2(index,index2)">回复</el-button>
                    </div>
                    <div
                      v-if="index2 === flog2 && index === flog1 && flogBox2"
                      class="second-wrapper"
                    >
                      <first-comment-box
                        :userInfoData="userInfoData"
                        :userName="userName"
                        @_sendReturnCommentData="_sendReturnCommentData2"
                      ></first-comment-box>
                    </div>
                  </li>
                </ul>
              </div>
            </li>
          </ul>
        </div>
        <recommend :recommendData="recommendData" />
      </div>
      <div class="actions">
        <ul>
          <li @click="star()">
            <button>赞</button>
          </li>
          <li @click="gotoPreRz()">
            <button :disabled="preDisabled" :style="{color: preDisabled ? '#999' : '#666'}">上一篇</button>
          </li>
          <li @click="gotoNextRz()">
            <button :disabled="nextDisabled" :style="{color: nextDisabled ? '#999' : '#666'}">下一篇</button>
          </li>
          <li @click="toComment()">
            <button>评论</button>
          </li>
          <li @click="addBrower()">
            <button>加入收藏</button>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { slider } from "@/public/slider.js";
import recommend from "@/components/comment/recommend";
import { indexUrl } from "@/public/uri.js";
import sendMessage from "@/components/comment/sendMessage.vue";
import userInfo from "@/components/comment/userInfo.vue";
import firstCommentBox from "@/components/comment/firstCommentBox.vue";
import { mapState, mapActions } from "Vuex";
export default {
  name: "read-rz",
  components: {
    "user-info": userInfo,
    "first-comment-box": firstCommentBox,
    "send-message": sendMessage,
    recommend
  },
  data() {
    return {
      id: "",
      aggregateData: {},
      flog1: -1,
      flog2: -1,
      flogBox1: false,
      flogBox2: false,
      preDisabled: false,
      nextDisabled: false,
      limit: 10,
      skip: 0,
      recommendData: ""
    };
  },
  filters: {
    starsFilters(data) {
      let newData = [];
      for (let i = 0; i < data.length; i++) {
        if (!data[i].commentId) {
          newData.push(data[i]);
        }
      }
      return newData.length;
    },
    commentStarFilters(data, comment) {
      let newData = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].commentId && comment.rzCommentId === data[i].commentId) {
          newData.push(data[i]);
        }
      }
      return newData.length;
    }
  },
  activated() {
    this.id = this.$route.params.id;
  },
  watch: {
    $route(now, pre) {
      if (pre.name === "/rz_id" && now.name === "/rz_id") {
        this.id = now.params.id;
      }
    },

    // 监听id值得变化进行执行数据的获取。
    id() {
      if (this.id) {
        // 根据日志获取当前日志数据并且关联日志作者数据和作者的旗下所有日志数据和相关评论数据
        this.aggregateData = {};
        this.getIdRzInUser({ id: this.id })
          .then(res => {
            this.aggregateData = res.data.data;
            this.$nextTick(() => {
              slider(document.getElementsByClassName("item-slide")[0]);
            });
            let length = this.aggregateData.allrz.length;
            if (length) {
              let activeLength = this._computeActiveLength();
              if (length === 1) {
                this.preDisabled = true;
                this.nextDisabled = true;
              } else {
                if (activeLength === 0) {
                  this.preDisabled = true;
                  this.nextDisabled = false;
                } else if (activeLength === length - 1) {
                  this.nextDisabled = true;
                  this.preDisabled = false;
                } else {
                  this.preDisabled = false;
                  this.nextDisabled = false;
                }
              }
            }

            this.getRecommendSkill({
              limit: this.limit,
              skip: this.skip,
              userName: this.aggregateData.userName
            })
              .then(res => {
                this.recommendData = res.data.data;
              })
              .catch(err => {
                console.log(err);
              });
          })
          .catch(err => {
            console.log(err);
          });
      }
    }
  },
  methods: {
    _sendMessageToUser(skillCommentData, data) {
      if (this.userName) {
        let collections = {
          text: skillCommentData,
          sendUserName: this.userInfoData.userName || this.userName,
          userName: data,
          sendCoverUrl: this.userInfoData.coverUrl || "",
          system: true,
          id: this.aggregateData._id,
          label: this.aggregateData.label,
          type: this.$route.path.split("/")[1]
        };
        this.sendMessageToUser(collections)
          .then(res => {
            console.log("ok");
          })
          .catch(err => {
            console.log("错误信息：" + err);
          });
      } else {
        alert("你还未登录，无法给作者留言！");
      }
    },
    sendMessage() {
      // 给文章作者发送留言
      if (this.userName) {
        this.$prompt("请输入要发送的内容", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
          .then(({ value }) => {
            if (value) {
              this.sendMessageToUser({
                text: value,
                sendUserName: this.userInfoData.userName || this.userName,
                userName: this.aggregateData.user[0].userName,
                sendCoverUrl: this.userInfoData.coverUrl || ""
              })
                .then(res => {
                  this.$alert(res.data.data);
                })
                .catch(err => {
                  console.log("错误信息：" + err);
                });
            } else {
              alert("检测内容为空，未提交数据！");
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        alert("你还未登录，无法给作者留言！");
      }
    },
    commentStar(commentId) {
      // 点赞
      let ip = returnCitySN.cip;
      let activeLength = this._computeActiveLength();
      this.setStar({
        id: this.aggregateData.allrz[activeLength].rzId,
        ip,
        commentId
      })
        .then(res => {
          this.getIdRzInUser({ id: this.id }).then(res => {
            this.aggregateData = res.data.data;
          });
          alert(res.data.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    gotoPreRz() {
      // 上一篇日志
      let activeLength = this._computeActiveLength();

      if (activeLength === 0) {
        alert("当前是第一篇文章。");
      } else {
        this.$router.push(
          "/rz/" + this.aggregateData.allrz[activeLength - 1]._id
        );
      }
    },
    gotoNextRz() {
      let activeLength = this._computeActiveLength();
      if (activeLength === this.aggregateData.allrz.length - 1) {
        alert("当前是最后一篇文章。");
      } else {
        this.$router.push(
          "/rz/" + this.aggregateData.allrz[activeLength + 1]._id
        );
      }
    },

    _computeActiveLength() {
      let data = this.aggregateData.allrz;
      let activeLength = 0;

      for (let i = 0; i < data.length; i++) {
        if (data[i]._id === this.id) {
          activeLength = i;
          break;
        }
      }
      return activeLength;
    },
    star() {
      // 点赞
      let ip = returnCitySN.cip;
      let activeLength = this._computeActiveLength();
      this.setStar({
        id: this.aggregateData.allrz[activeLength].rzId,
        ip,
        parentFlog: true
      })
        .then(res => {
          this.getIdRzInUser({ id: this.id }).then(res => {
            this.aggregateData = res.data.data;
          });
          alert(res.data.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    toComment() {
      location.href = "#/comment-box";
      this.$refs.sendMessageElement.$refs.commentBox.focus();
    },
    addBrower() {
      let sURL = indexUrl + this.$route.path;
      const sTitle = "共享资源";

      sURL = encodeURI(sURL);
      try {
        window.external.addFavorite(sURL, sTitle);
      } catch (e) {
        try {
          window.sidebar.addPanel(sTitle, sURL, "");
        } catch (e) {
          alert(
            "您的浏览器不支持自动加入收藏功能，请使用Ctrl+D进行添加，或手动在浏览器里进行设置！"
          );
        }
      }
    },
    gotoThis(id) {
      // 点击列表上的数据跳转到对应的页面。
      if (id) {
        this.$router.push("/rz/" + id);
      } else {
        console.log("出错：" + id + "的数据有问题！");
      }
    },
    showReturnArea2(index, index2) {
      this.flog1 = index;
      this.flog2 = index2;
      this.flogBox1 = false;
      this.flogBox2 = true;
    },
    _sendReturnCommentData2(data) {
      //回复子组件的评论
      let activeLength = this._computeActiveLength();
      let returnUserName = this.aggregateData.comment[this.flog1].child[
        this.flog2
      ].returnUserName;
      let collections = {
        rzId: this.aggregateData.allrz[activeLength].rzId,

        userUserName: returnUserName,
        rzCommentId: this.aggregateData.comment[this.flog1].child[this.flog2]
          .rzCommentId,
        rzCommentData: this.aggregateData.comment[this.flog1].child[this.flog2]
          .returnText,
        userCoverUrl: this.aggregateData.comment[this.flog1].child[this.flog2]
          .returnCoverUrl,

        returnText: data,
        returnUserName: this.userInfoData.userName,
        returnCoverUrl: this.userInfoData.coverUrl || ""
      };

      this.setRzChildCommentData(collections)
        .then(res => {
          if (res.data.ok === 1) {
            this.getIdRzInUser({ id: this.id }).then(res => {
              this.aggregateData = res.data.data;
              this.flogBox2 = false;
            });

            this._sendMessageToUser(data, returnUserName);

            alert(res.data.data);
          } else {
            alert(res.data.data);
          }
        })
        .catch(err => {
          alert("错误提示：" + err);
        });
    },
    _sendReturnCommentData(data) {
      // 子组件点击发送的回调方法
      let activeLength = this._computeActiveLength();
      let collections = {
        rzId: this.aggregateData.allrz[activeLength].rzId,

        userUserName: this.aggregateData.comment[this.flog1].sendUserName,
        rzCommentId: this.aggregateData.comment[this.flog1].rzCommentId,
        rzCommentData: this.aggregateData.comment[this.flog1].rzCommentData,
        userCoverUrl: this.aggregateData.comment[this.flog1].sendUserCoverUrl,

        returnText: data,
        returnUserName: this.userInfoData.userName,
        returnCoverUrl: this.userInfoData.coverUrl || ""
      };

      this.setRzChildCommentData(collections)
        .then(res => {
          if (res.data.ok === 1) {
            this.getIdRzInUser({ id: this.id }).then(res => {
              this.aggregateData = res.data.data;
            });

            this._sendMessageToUser(
              data,
              this.aggregateData.comment[this.flog1].sendUserName
            );
            alert(res.data.data);
          } else {
            alert(res.data.data);
          }
        })
        .catch(err => {
          alert("错误提示：" + err);
        });
    },
    showReturnArea(index) {
      this.flog1 = index;
      this.flogBox1 = true;
      this.flogBox2 = false;
    },
    sendCommentData(data) {
      let collections = {
        rzId: this.aggregateData.rzId,
        rzUserName: this.aggregateData.user[0].userName,
        rzCommentData: data,
        sendUserName: this.userInfoData.userName,
        sendUserCoverUrl: this.userInfoData.coverUrl || ""
      };
      this.setRzCommentData(collections)
        .then(res => {
          if (res.data.ok === 1) {
            this.getIdRzInUser({ id: this.id }).then(res => {
              this.aggregateData = res.data.data;
            });

            this._sendMessageToUser(data, this.aggregateData.user[0].userName);

            alert(res.data.data);
          } else {
            res.data.data;
          }
        })
        .catch(err => {
          alert("错误提示：" + err);
        });
    },
    ...mapActions("user", [
      "getIdRzInUser",
      "setRzCommentData",
      "setRzChildCommentData",
      "setStar",
      "sendMessageToUser",
      "getRecommendSkill"
    ])
  },
  computed: {
    ...mapState("user", ["userInfoData", "userName"])
  }
};
</script>

<style lang="sass" scoped>
@import '@/assets/default.sass'
.read-rz
  width: 100%
  height: 100%
  background-color: #eee
  padding: 20px 0
  min-height: 93vh
  .rz-wrapper
    width: 1280px
    height: 100%
    margin: 0 auto
    @include flex(space-between,flex-start)
    .user
      flex: 0 0 25%
      width: 25%
      overflow: hidden
      .allrz
        width: 100%
        margin-top: 10px  
        background-color:#fff
        overflow: hidden
        .title
          padding-left: 10px
          border-bottom: 1px solid #eee
          width: 100%
          height: 30px
          line-height: 30px
          @include title-before(5px,16px,7px,0px,#eb2001)
        .item
          width: 100%
          overflow: hidden
          >ul
            width: 100%
            padding: 10px
            overflow: hidden
            >li
              width: 100%
              height: 40px
              overflow: hidden
              cursor: pointer
              padding: 5px 
              transition: all .3s
              @include flex(space-between,center)
              .label
                flex: 1
                padding-right: 5px
                @include text-overflow()
              .date
                flex: 0 0 30%
                display: block
                color: #999
                @include text-overflow()
              &:hover:not(.active)
                background-color: #eee
                transition: all .3s
            .active
              color: #eb2001
    .rz-content
      flex: 0 0 67%
      width: 67%
      overflow: hidden
      background-color: #fff      
      .author-info-data
        padding: 2%
        width: 100%
        overflow: hidden
        .label
          width: 100%
          padding: 0 0 10px
          border-bottom: 10px solid #eee
          .name
            width: 100%
            height: 40px
            font-size: 24px
            font-weight: 700
            @include flex(space-between,center)
            .star
              font-size: 14px
              font-weight: 200
              display: block
              >i
                color: #eb2001
                font-size: 14px
                font-weight: 200
          .date
            width: 100%
            height: 30px
            line-height: 30px
            @include flex(space-between,center)
            >span
              flex: 1
              color: #333
              display: block
              @include text-overflow()
            >p
              color: #999
              flex: 0 0 55%
              width: 55%
              @include flex(space-between,center)
              >span
                display: block
                text-align: right
                flex: 1
                width: 50%
                @include text-overflow()
        .body
          width: 100%
          padding: 40px 0
          overflow: hidden
          border-bottom: 10px solid #eee
          .body-wrapper
            width: 100%
            .img
              >img
                padding: 0 10px 10px 0
                width: 300px
                height: auto
                float: left 
            >p
              line-height: 1.5
              letter-spacing: 0.05em
              text-indent: 1em
              white-space: pre-wrap
              &:first-line
                color: #333
                font-size: 18px
           
      .comment
        padding: 2%
        width: 100%
        border-bottom: 10px solid #eee
        >ul
          width: 100%
          >li
            width: 100%
            padding: 20px 10px
            border-bottom: 5px dotted #eee
            overflow: hidden
            .comment-show
              width: 100%
              height: 32px
              position: relative
              @include flex(flex-start,center)
              .cover
                flex: 0 0 32px
                height: 100%
                overflow: hidden
                border-radius: 5px
                @include flex(center,center)
                img
                  width: 100%
                  height: auto
              span
                margin-left: 20px
              .userName
                color: #000
                font-weight: 700
              .z-index
                position: absolute
                right: 160px
                width: 60px
                height: 100%
                color: #aaa
                @include flex(center,center)
              .btn
                position: absolute 
                right: 0
                @include flex(center,center)
                .badge
                  margin-right: 30px
            .comment-body
              margin-top: 5px
              line-height: 20px
              min-height: 40px
              padding: 0 52px
            .comment-child
              >ul
                width: 100%
                padding: 10px
                >li
                  border: 1px solid #f0f0f0
                  padding: 20px
                  overflow: hidden
                  margin-bottom: 5px
                  flex-wrap: wrap
                  @include flex(flex-start,flex-start)            
                  .return-user
                    flex: 0 0 80%
                    overflow: hidden
                    >p
                      width: 100%
                      height: 25px
                      overflow: hidden
                      text-overflow: ellipsis
                      white-space: nowrap
                      >i
                        color: #999                  
                    >.return-text
                      width: 100%
                      line-height: 25px
                      color: #0487dc
                      padding: 0 10px
                  .return-right
                    flex: 1
                    text-align: right
                    >p
                      height: 25px  
                  .second-wrapper            
                    flex: 0 0 100%  
    .actions
      flex: 0 0 6%   
      width: 6%
      background-color: #fff   
      overflow: hidden
      >ul
        width: 100%
        text-align: center
        >li
          width: 100%
          height: 30px
          line-height: 30px
          border-bottom: 1px solid #eee
          cursor: pointer  
          >button
            width: 100%
            height: 100%
          &:hover
            background-color: #fafafa
</style>